package com.jfblog.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;

import com.jfblog.bean.CacheBean;
import com.jfblog.bean.Constants;
import com.jfblog.common.JFBlogCache;
import com.jfblog.interceptor.BlackInterceptor;
import com.jfblog.model.Article;
import com.jfblog.model.Message;
import com.jfblog.model.Tags;
import com.jfblog.model.User;
import com.jfblog.utils.HtmlUtil;
import com.jfblog.utils.LuceneUtil;
import com.jfblog.utils.PageUtil;
import com.jfblog.utils.RequestUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * 
 * @ClassName: IndexController
 * @Description: 首页访问(这里用一句话描述这个类的作用)
 * @author Realfighter
 * @date 2014-12-6 下午04:08:22
 * 
 */
public class IndexController extends Controller {

	private static final Logger logger = Logger.getLogger(IndexController.class);

	/**
	 * 首页
	 * 
	 * @Title: index
	 * @author Realfighter void
	 * @throws
	 */
	public void index() {
		// 设置首页缓存信息
		JFBlogCache.setAllCache(this);
		int pagenum = 1;
		int pageSize = 7;// index每页七篇文章
		long tagid = 0;// 标签ID
		String time = "0-0";// 归档日期
		String searchKey = "";// 搜索关键字
		if (!isParaBlank(0)) {// 页码
			pagenum = getParaToInt(0);
		}
		if (!isParaBlank(1)) {// 标签ID
			tagid = getParaToInt(1);
		}
		if (!isParaBlank(2) && !isParaBlank(3)) {// 归档日期
			time = getPara(2) + "-" + getPara(3);
		}
		if (!isParaBlank(4)) {// 关键字
			try {
				searchKey = URLDecoder.decode(URLDecoder.decode(getPara(4), "UTF-8"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// 解码错误不处理
				searchKey = "";
			}
		}
		Page<Article> page = null;
		if (!"".equals(searchKey)) {
			// lucene检索
			String aids = LuceneUtil.searchString(searchKey);
			page = Article.dao.findArticle4PageByKey(pagenum, pageSize, searchKey, aids);
		} else {
			page = Article.dao.findArticles4Page(pagenum, pageSize, tagid, time, 0, false);
		}
		setAttr("search_key", searchKey);
		setAttr("index_tagid", tagid);
		setAttr("index_time", time);
		setAttr("page", new PageUtil(page));
		render("index.jsp");
	}

	/**
	 * 留言信息
	 * 
	 * @Title: message
	 * @author Realfighter void
	 * @throws
	 */
	public void message() {
		// 留言信息
		generateMessageMap(this);
		// 设置首页缓存信息
		JFBlogCache.setAllCache(this);
		render("message.jsp");
	}

	@SuppressWarnings("unchecked")
	private void generateMessageMap(Controller controller) {
		int type = controller.getParaToInt(0);// 文章标识ID
		setAttr("articletag", type);
		if (type > 0) {// 文章需要记录阅读数
			Article art = Article.dao.findById(type);
			int count = art.getInt("clicks");
			count++;
			art.set("clicks", count);
			art.update();// 阅读数
		}
		switch (type) {
		case Constants.archive:// 归档信息
			List<Article> archives = Article.dao.findArchives();
			setAttr("archives", archives);
			break;
		case Constants.cates:// category分类
			String category = null;
			try {
				category = URLDecoder.decode(URLDecoder.decode(getPara(2), "UTF-8"), "UTF-8");
			} catch (Exception e) {
				logger.error("中文转码或参数传递异常，默认显示所有分类：" + e);
			}
			List<Tags> tags = Tags.dao.findByCategory(category);
			setAttr("cate_para", getPara(2));
			setAttr("cate_tags", category == null ? "所有分类" : category);
			setAttr("catetags", tags);
			break;
		}
		if (type > 0) {// 文章需要详情展示,显示上一篇下一篇
			Article article = Article.dao.findArticleInfoById(type);
			setAttr("article", article);
			List<Article> articles = Article.dao.findArticlePrevAndNextById(type);
			setAttr("article2", articles);
		}
		int pageNum = 1;
		if (controller.isParaExists(1)) {
			pageNum = controller.getParaToInt(1);
		}
		Page<Message> msgPage = (Page<Message>) Message.dao.findMsg4Page(pageNum, 10, 0, type, true, true);
		controller.setAttr("msgPage", new PageUtil(msgPage));
		Map<String, List<Message>> msgMap = new HashMap<String, List<Message>>();
		for (Message msg : msgPage.getList()) {
			List<Message> msgList = (List<Message>) Message.dao.findMsg4Page(null, null, msg.getInt("id"), type, false,
					false);
			msgMap.put(msg.getInt("id").toString(), msgList);
		}
		controller.setAttr("msgMap", msgMap);
	}

	/**
	 * 判断用户名或密码是否正确
	 */
	public void isNameCorrect() {
		String text = "";
		// 先判断用户名是否存在，不存在的话返回''，可以注册
		User user = User.dao.findByName(getPara("name"));
		if (user != null) {
			// 如果用户名存在，判断密码是否正确
			if (!user.getStr("pwd").equals(getPara("pwd"))) {
				// 密码不正确
				text = "用户名已存在，密码错误";
			}
		}
		renderText(text);
	}

	/**
	 * 留言信息保存 增加黑名单过滤
	 */
	@Before( { BlackInterceptor.class, Tx.class })
	public void save() {
		String returnUrl = getPara("returnUrl");
		setAttr("returnUrl", returnUrl);
		Object userSessionID = getSessionAttr("xx566_userid");
		int userid = 0;
		try {
			userid = (Integer) userSessionID;
		} catch (Exception e) {
			userid = 0;
		}
		User user;
		if (userid == 0) {
			user = getModel(User.class);// 留言的user
			// 根据用户名或密码获取user
			User _user = User.dao.findLoginUser(user.getStr("name"), user.getStr("pwd"));
			if (_user == null) {// 如果用户为空，表示为新用户注册
				Random r = new Random();
				int num = r.nextInt(9) + 1;// 1-9的整数
				user.set("avatar", "image/" + num + ".jpg");
				user.set("userip", RequestUtil.getIpAddr(getRequest()));
				user.save();
			} else {
				// 更新用户的网站信息
				if (!"".equals(user.getStr("website")) && user.getStr("website").startsWith("http://")) {
					_user.set("website", user.getStr("website"));
				}
				_user.update();
				user = _user;// 老用户
			}
			setSessionAttr("xx566_userid", user.getInt("id"));
			// 设置用户名和用户头像信息
			setSessionAttr("xx566_username", user.getStr("name"));
			setSessionAttr("xx566_userpic", user.getStr("avatar"));
		} else {
			user = User.dao.findById(userid);
		}
		if (!isParaBlank("message.content")) {
			Message message = getModel(Message.class).set("userid", user.getInt("id"));
			// 处理留言信息中的html信息，防止xss
			String content = HtmlUtil.changeTag(message.getStr("content"));
			// content = HtmlUtil.changeTag(content);
			message.set("content", content).save();
			// 更新缓存
			CacheKit.put(CacheBean.MESSAGES, CacheBean.MESSAGES, Message.dao.findMsg4Page(1, 10));
		}
		redirect(returnUrl);
	}

	/**
	 * 关于Realfighter功能
	 */
	public void about() {
		Article realfighter = Article.dao.findById(Constants.Realfighter);
		setAttr("realfighter", realfighter);
		// 留言信息
		generateMessageMap(this);
		// 设置首页缓存信息
		JFBlogCache.setAllCache(this);
		render("about.jsp");
	}

	/**
	 * 文章归档查询
	 */
	public void archive() {
		List<Article> archives = Article.dao.findArchives();
		setAttr("archives", archives);
		// 留言信息
		generateMessageMap(this);
		// 设置首页缓存信息
		JFBlogCache.setAllCache(this);
		render("archive.jsp");
	}

	/**
	 * 文章详情查询
	 */
	public void detail() {
		// 留言信息
		generateMessageMap(this);
		// 设置首页缓存信息
		JFBlogCache.setAllCache(this);
		render("detail.jsp");
	}

	/**
	 * 导航分类查询
	 */
	public void cates() {
		// 留言信息
		generateMessageMap(this);
		// 设置首页缓存信息
		JFBlogCache.setAllCache(this);
		render("cates.jsp");
	}

}
